from fastapi import APIRouter, Request, HTTPException, Header
from fastapi.responses import JSONResponse
from app.services.shopify_payment_service import (
    verify_webhook_signature,
    process_payment_webhook,
    process_refund_webhook
)
from app.utils.response_handler import SuccessResponse
import logging
import traceback
import json

# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
router = APIRouter(prefix="/api/v1/webhooks/shopify")


@router.post("/orders/create")
async def handle_order_create(
    request: Request,
    x_shopify_hmac_sha256: str = Header(..., alias="X-Shopify-Hmac-SHA256"),
    x_shopify_shop_domain: str = Header(..., alias="X-Shopify-Shop-Domain"),
    x_shopify_topic: str = Header(..., alias="X-Shopify-Topic")
):
    """
    处理Shopify订单创建webhook
    当用户完成支付后，Shopify会发送此webhook
    """
    try:
        # 获取原始请求体
        body_bytes = await request.body()
        
        # 验证webhook签名
        is_valid = verify_webhook_signature(x_shopify_hmac_sha256, body_bytes)
        if not is_valid:
            logging.warning(f"无效的webhook签名，来源: {x_shopify_shop_domain}")
            return JSONResponse(
                status_code=401,
                content={"status": "error", "message": "Invalid webhook signature"}
            )
        
        # 解析请求体
        order_data = json.loads(body_bytes)
        
        # 优先从请求体获取shopify_domain，如果没有则使用请求头中的值
        shopify_domain = order_data.get('shopify_domain', x_shopify_shop_domain)
        
        logging.info(f"收到订单创建webhook: 店铺={shopify_domain}, 订单ID={order_data.get('id')}")
        
        # 处理支付并充值积分
        result = process_payment_webhook(shopify_domain, order_data)
        
        if result["success"]:
            logging.info(f"积分充值成功: {result}")
            # Shopify要求webhook返回200状态码表示接收成功
            return JSONResponse(
                status_code=200,
                content={"status": "success", "message": "Webhook processed successfully"}
            )
        else:
            logging.error(f"积分充值失败: {result}")
            # 仍然返回200，因为webhook已接收，只是处理有问题
            return JSONResponse(
                status_code=200,
                content={"status": "warning", "message": f"Processing failed: {result['message']}"}
            )
            
    except json.JSONDecodeError as e:
        logging.error(f"解析webhook数据失败: {e}")
        return JSONResponse(
            status_code=400,
            content={"status": "error", "message": "Invalid JSON data"}
        )
    except Exception as e:
        logging.error(f"处理订单创建webhook异常: {e}\n{traceback.format_exc()}")
        # 捕获所有异常，确保返回200，避免Shopify重试
        return JSONResponse(
            status_code=200,
            content={"status": "error", "message": "Internal processing error"}
        )


@router.post("/refunds/create")
async def handle_refund_create(
    request: Request,
    x_shopify_hmac_sha256: str = Header(..., alias="X-Shopify-Hmac-SHA256"),
    x_shopify_shop_domain: str = Header(..., alias="X-Shopify-Shop-Domain")
):
    """
    处理Shopify退款创建webhook
    当订单被退款时，Shopify会发送此webhook
    """
    try:
        # 获取原始请求体
        body_bytes = await request.body()
        
        # 验证webhook签名
        is_valid = verify_webhook_signature(x_shopify_hmac_sha256, body_bytes)
        if not is_valid:
            logging.warning(f"无效的webhook签名，来源: {x_shopify_shop_domain}")
            return JSONResponse(
                status_code=401,
                content={"status": "error", "message": "Invalid webhook signature"}
            )
        
        # 解析请求体
        refund_data = json.loads(body_bytes)
        
        # 优先从请求体获取shopify_domain，如果没有则使用请求头中的值
        shopify_domain = refund_data.get('shopify_domain', x_shopify_shop_domain)
        
        logging.info(f"收到退款创建webhook: 店铺={shopify_domain}, 退款ID={refund_data.get('id')}")
        
        # 处理退款
        result = process_refund_webhook(shopify_domain, refund_data)
        
        # 无论成功失败都返回200
        return JSONResponse(
            status_code=200,
            content={
                "status": "success" if result["success"] else "warning",
                "message": result["message"]
            }
        )
        
    except Exception as e:
        logging.error(f"处理退款webhook异常: {e}\n{traceback.format_exc()}")
        return JSONResponse(
            status_code=200,
            content={"status": "error", "message": "Internal processing error"}
        )


@router.get("/test")
async def test_webhook_endpoint():
    """
    测试Shopify webhook端点是否正常工作
    """
    return SuccessResponse(
        data={
            "message": "Shopify webhook endpoints are ready",
            "available_endpoints": [
                "/api/v1/webhooks/shopify/orders/create",
                "/api/v1/webhooks/shopify/refunds/create"
            ]
        }
    )